package com.modules.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.models.constant.MessageConstant;
import com.modules.utils.BeanUtils;

@ControllerAdvice
public class GlobalExceptionHandler {
	 private static Logger logger	= LoggerFactory.getLogger(GlobalExceptionHandler.class);
	@ExceptionHandler(value=Exception.class) 
	@ResponseBody
    public Object  allExceptionHandler(HttpServletRequest request,  
            Exception exception) throws Exception  
    {  	
		logger.info(exception.getMessage());
		exception.printStackTrace();
			/**
			 * 判断请求类型是不是ajax的
			 * */
		
			if(BeanUtils.isAjaxRequest(request)){
				Map<String, Object> tips = new HashMap<String, Object>();
				tips.put(MessageConstant.SUCCESS, false);
				tips.put(MessageConstant.MSG,exception.getMessage());
				return tips;
			}else{
				ModelAndView mv = new ModelAndView();  
			 	if(exception instanceof UnauthorizedException){    
			 		 mv.addObject("roncooException", exception.getMessage());
				     mv.setViewName("/noauthorized"); 
		        } else {
		        	 mv.addObject("roncooException", exception.getMessage());
				     mv.setViewName("redirect:/error"); 
		        }
		        return mv;
			}
			
    }  
}
